package cn.zzq.aix.nativeinterface.javareflector;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;

import com.google.appinventor.components.runtime.collect.Lists;

import cn.zzq.aix.nativeinterface.javareflector.parser.MethodPatternTextParser;
import cn.zzq.aix.nativeinterface.javareflector.parser.PatternTextParser;

public class TextReflectUtil {
	public static ClassManager classManager = ClassManager.getClassManager();

	/**
	 * @param pattern 形如[类型名].[方法名]<类型名1,类型名2>，例如java.lang.StringBuffer.append<boolean>
	 * @return
	 * @throws NoSuchMethodException
	 * @throws ClassNotFoundException
	 */
	public static Method getMethodByPattern(String patternText) throws ClassNotFoundException, NoSuchMethodException {
		MethodPatternTextParser mptp = new MethodPatternTextParser(patternText);
		Class<?> class_ = classManager.get(mptp.getClassName());
		String methodName = mptp.getMethodName();
		ArrayList<Class<?>> typeClasses = getTypesByClassNames(mptp);
		return ReflectUtil.getMethod(class_, methodName, typeClasses.toArray(new Class<?>[typeClasses.size()]));
	}

	/**
	 * 用字符串获取此 Class 对象所表示的类的公共构造方法
	 * 
	 * @param pattern 字符串格式为 类名称<参数类型字符串>，例如java.lang.StringBuffer<int>
	 * @return 此 Class 对象所表示的类的公共构造方法
	 * @throws NoSuchMethodException
	 * @throws ClassNotFoundException
	 */
	public static Constructor<?> getConstructorByPattern(String patternText)
			throws ClassNotFoundException, NoSuchMethodException {
		PatternTextParser ptp = new PatternTextParser(patternText);
		Class<?> class_ = classManager.get(ptp.getKey());
		ArrayList<Class<?>> typeClasses = getTypesByClassNames(ptp);
		return ReflectUtil.getConstructor(class_, typeClasses.toArray(new Class<?>[typeClasses.size()]));

	}

	/**
	 * 通过字符串列表获取类对象列表，比如传入列表[int, double, java.lang.String]可以获取到对应的类型对象列表
	 * 
	 * @param classNames 类型名称列表
	 * @return 类对象数组
	 * @throws ClassNotFoundException
	 */
	public static ArrayList<Class<?>> getTypesByClassNames(ArrayList<String> classNames) throws ClassNotFoundException {
		ArrayList<Class<?>> result = Lists.newArrayList();
		if (classNames.isEmpty()) {
			return result;
		}
		for (String className : classNames) {
			result.add(classManager.get(className));
		}
		return result;
	}

	/**
	 * 通过字符串获取类对象数组，比如输入int, double, java.lang.String可以获取到对应的类型对象数组
	 * 
	 * @param str 字符串
	 * @return 类对象数组
	 * @throws ClassNotFoundException
	 */
	public static Class<?>[] getTypesByText(String str) throws ClassNotFoundException {
		if (str.isEmpty()) {
			return new Class<?>[0];
		}
		String[] strings = str.split(",");
		Class<?>[] types = new Class<?>[strings.length];
		for (int i = 0; i < types.length; i++) {
			types[i] = ClassManager.getClassManager().get(strings[i].trim());
		}
		return types;
	}
}
